import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by loso on 2017/3/9.
 */
public class _202_HappyNumber {
    public static void main(String[] args) {
        _202_HappyNumber a = new _202_HappyNumber();
        System.out.println(a.isHappy(2));
    }
    List<Integer> numlist = new ArrayList<>();

    public boolean isHappy(int n) {
        numlist.clear();
        return check(n);

    }

    public boolean check(int n) {
        if (n == 1)
            return true;
        if (numlist.contains(n))
            return false;
        numlist.add(n);
        int num = 0;
        String s = Integer.toString(n);
        for (int i = 0; i < s.length(); i++) {
            num += (s.charAt(i) - '0') * (s.charAt(i) - '0');
        }

        return check(num);
    }


    public boolean isHappyBigBoss(int n) {
        Set<Integer> inLoop = new HashSet<Integer>();
        int squareSum,remain;
        while (inLoop.add(n)) {
            squareSum = 0;
            while (n > 0) {
                remain = n%10;
                squareSum += remain*remain;
                n /= 10;
            }
            if (squareSum == 1)
                return true;
            else
                n = squareSum;

        }
        return false;

    }
}
